package week_eight;

public class StringToIntegerAtoi_8 {
    public int myAtoi(String s) {
        int index = 0;
        int n = s.length();
        //1 while，丢弃空格
        while (index < n && s.charAt(index) == ' ') index++;

        //2. if判断符号
        int signed = 1;
        if (index < n && s.charAt(index) == '-') {
            index++;
            signed = -1;
        } else if (index < n && s.charAt(index) == '+') index++;
        // 3. while处理数字
        int ans = 0;
        while (index < n) {
            if (s.charAt(index) >= '0' && s.charAt(index) <= '9') {
                // 判断范围
                int tmp = s.charAt(index) - '0';
                if (ans > (Integer.MAX_VALUE - tmp) / 10) {
                    return signed == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
                }
                ans = ans * 10 + tmp;
                // System.out.println(index+" : "+s.charAt(index)+" ans: "+ ans);
                index++;
            } else break; // 4. 终止条件
        }

        return ans * signed;

    }
}
